package com.xbongbong.sso.service.imp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.ConfigConstant;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.EnableEnum;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.CommentUtil;
import com.xbongbong.paas.toolbox.util.DesUtil;
import com.xbongbong.paas.toolbox.util.OkHttpUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.util.URLEncodeUtils;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.enums.errorcodes.SsoErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.sso.domain.entity.OauthConnectorEntity;
import com.xbongbong.sso.domain.entity.OauthCustomParamEntity;
import com.xbongbong.sso.domain.entity.OauthParamEntity;
import com.xbongbong.sso.domain.entity.OauthStepEntity;
import com.xbongbong.sso.domain.entity.OauthUserEntity;
import com.xbongbong.sso.domain.entity.XbbUserEntity;
import com.xbongbong.sso.enums.AccountRuleEnum;
import com.xbongbong.sso.enums.ContentTypeEnum;
import com.xbongbong.sso.enums.MethodEnum;
import com.xbongbong.sso.enums.OauthFieldEnum;
import com.xbongbong.sso.enums.PositionEnum;
import com.xbongbong.sso.enums.SourceEnum;
import com.xbongbong.sso.enums.StageTypeEnum;
import com.xbongbong.sso.enums.StepTypeEnum;
import com.xbongbong.sso.help.CalculationHelp;
import com.xbongbong.sso.help.OauthConnectorHelp;
import com.xbongbong.sso.help.OauthCustomParamHelp;
import com.xbongbong.sso.help.OauthParamHelp;
import com.xbongbong.sso.model.OauthConnectorModel;
import com.xbongbong.sso.model.OauthParamModel;
import com.xbongbong.sso.model.OauthStepModel;
import com.xbongbong.sso.model.OauthUserModel;
import com.xbongbong.sso.model.XbbUserModel;
import com.xbongbong.sso.pojo.CustomParameterMapPojo;
import com.xbongbong.sso.pojo.OauthConnectorPojo;
import com.xbongbong.sso.pojo.ParameterMapPojo;
import com.xbongbong.sso.pojo.dto.GetOauthConnectorDTO;
import com.xbongbong.sso.pojo.dto.UserOauthDTO;
import com.xbongbong.sso.pojo.vo.GenerateNonceVO;
import com.xbongbong.sso.pojo.vo.GetOauthConnectorVO;
import com.xbongbong.sso.pojo.vo.OauthFlowVO;
import com.xbongbong.sso.pojo.vo.UserOauthVO;
import com.xbongbong.sso.service.OauthFlowService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 登录过程
 */
@Service("oauthFlowService")
public class OauthFlowServiceImpl implements OauthFlowService {
    private static final Logger LOG = LoggerFactory.getLogger(OauthFlowServiceImpl.class);

    @Resource
    private OauthConnectorModel oauthConnectorModel;
    @Resource
    private OauthStepModel oauthStepModel;
    @Resource
    private OauthParamModel oauthParamModel;
    @Resource
    private OauthUserModel oauthUserModel;
    @Resource
    private XbbUserModel xbbUserModel;
    @Resource
    private OauthConnectorHelp oauthConnectorHelp;
    @Resource
    private OauthParamHelp oauthParamHelp;
    @Resource
    private ProBaseConfig proBaseConfig;
    @Resource
    private PaasRedisHelper paasRedisHelper;
    @Resource
    private CalculationHelp calculationHelp;


    @Override
    public GetOauthConnectorVO getOauthConnector(GetOauthConnectorDTO getOauthConnectorDTO) throws XbbException {
        String connectorSign = getOauthConnectorDTO.getConnectorSign();
        Map<String, Object> param = new HashMap<>();
        param.put("connectorSign", connectorSign);
        param.put("enable", EnableEnum.OPEN.getCode());
        param.put("del", DelEnum.NORMAL.getDel());
        List<OauthConnectorEntity> oauthConnectors = oauthConnectorModel.findEntities(param);
        if (CollectionsUtil.isEmpty(oauthConnectors)) {
            throw new XbbException(SsoErrorCodeEnum.API_ERROR_273003);
        }
        List<OauthConnectorPojo> list = new ArrayList<>();
        for (OauthConnectorEntity oauthConnector : oauthConnectors) {
            list.add(oauthConnectorHelp.oauthConnectorPojoFormat(oauthConnector));
        }
        GetOauthConnectorVO getOauthConnectorVO = new GetOauthConnectorVO();
        getOauthConnectorVO.setList(list);
        return getOauthConnectorVO;
    }

    @Override
    public UserOauthVO userOauth(UserOauthDTO userOauthDTO) throws XbbException {
        OauthConnectorEntity oauthConnector = oauthConnectorModel.getByConnectorSign(userOauthDTO.getConnectorSign());
        if (Objects.isNull(oauthConnector)) {
            throw new XbbException(SsoErrorCodeEnum.API_ERROR_273003);
        }
        List<OauthStepEntity> oauthSteps = oauthStepModel.getByConnectorId(oauthConnector.getCorpid(),
                oauthConnector.getId(), EnableEnum.OPEN.getCode());
        if (CollectionsUtil.isEmpty(oauthSteps)) {
            throw new XbbException(SsoErrorCodeEnum.API_ERROR_273006);
        }
        OauthStepEntity oauthStep = oauthSteps.get(0);
        Integer stepType = oauthStep.getStepType();
        ParameterMapPojo parameterMapPojo = oauthParamHelp.getParameterMap(oauthConnector);
        Map<String, String> constantParameterMap = parameterMapPojo.getConstantParameterMap();
        Map<String, OauthCustomParamEntity> calculationCustomParameterMap = parameterMapPojo.getCalculationCustomParameterMap();
        UserOauthVO userOauthVO = new UserOauthVO();
        if (Objects.equals(stepType, StepTypeEnum.AUTH_CODE.getCode())) {
            userOauthVO = authCodeUrl(oauthConnector, oauthStep);
            return userOauthVO;
        } else if (Objects.equals(stepType, StepTypeEnum.ACCESS_TOKEN.getCode())){
            OauthFlowVO oauthFlowVO = new OauthFlowVO();
            accessToken(oauthConnector, constantParameterMap, calculationCustomParameterMap);
            if (userMatching(oauthConnector, constantParameterMap, oauthFlowVO)) {
                userOauthVO.setLoginUrl(oauthFlowVO.getLoginUrl());
                return userOauthVO;
            }
        } else if (Objects.equals(stepType, StepTypeEnum.ID_AUTH.getCode())) {
            OauthFlowVO oauthFlowVO = new OauthFlowVO();
            identityAuthentication(oauthConnector, constantParameterMap, calculationCustomParameterMap);
            if (userMatching(oauthConnector, constantParameterMap, oauthFlowVO)) {
                userOauthVO.setLoginUrl(oauthFlowVO.getLoginUrl());
                return userOauthVO;
            }
        }
        //走完所有的步骤，没有用户匹配参数
        throw new XbbException(SsoErrorCodeEnum.API_ERROR_273013);
    }

    @Override
    public String getRedirectLoginUrl(String sign) throws XbbException {
        OauthConnectorEntity oauthConnector = oauthConnectorModel.getByConnectorSign(sign);
        if (Objects.isNull(oauthConnector)) {
//            throw new XbbException(SsoErrorCodeEnum.API_ERROR_273003);
            return proBaseConfig.getRedirectLoginUrl() + "?sign=" + sign
                    + "&errorMsg=" + URLEncodeUtils.encodeURL(SsoErrorCodeEnum.API_ERROR_273003.getMsg());
        }
        String corpid = oauthConnector.getCorpid();
        String source = "";
        if (corpid.indexOf(SourceEnum.DINGDING.getAlias()) == 0) {
            source = SourceEnum.DINGDING.getAlias();
        } else if (corpid.indexOf("ww") == 0
                || corpid.indexOf(SourceEnum.QIWEI.getAlias()) == 0
                || corpid.indexOf("wp") == 0) {
            source = SourceEnum.QIWEI.getAlias();
        } else if (corpid.indexOf(SourceEnum.XBB.getAlias()) == 0) {
            source = SourceEnum.XBB.getAlias();
        } else {
            source = SourceEnum.FEISHU.getAlias();
        }
        String url = proBaseConfig.getRedirectLoginUrl() + "?sign=" + sign + "&source=" + source;
        return url;
    }

    /**
     *
     * @param oauthConnector
     * @param oauthStep Auth Code步骤信息
     * @return
     */
    private UserOauthVO authCodeUrl(OauthConnectorEntity oauthConnector, OauthStepEntity oauthStep) throws XbbException {
        ParameterMapPojo parameterMapPojo = oauthParamHelp.getParameterMap(oauthConnector);
        Map<String, String> constantParameterMap = parameterMapPojo.getConstantParameterMap();
        Map<String, OauthCustomParamEntity> calculationCustomParameterMap = parameterMapPojo.getCalculationCustomParameterMap();
        List<OauthParamEntity> oauthParams = oauthParamModel.getOauthParams(oauthStep.getCorpid(), oauthStep.getId(),
                StageTypeEnum.REQUEST.getCode(), EnableEnum.OPEN.getCode());
        Map<String, String> headerMap = getHeaderParam(oauthParams, constantParameterMap, calculationCustomParameterMap);
        Map<String, Object> bodyMap = getBodyParam(oauthParams, constantParameterMap, calculationCustomParameterMap);
        String url = oauthStep.getUrl();
        if (StringUtil.isEmpty(url)) {
            throw new XbbException(SsoErrorCodeEnum.API_ERROR_273013);
        }
        String oauthCodeUrl = url + CommentUtil.commonMapAppendToUrl(bodyMap);
        UserOauthVO userOauthVO = new UserOauthVO();
        JSONObject oauthCode = new JSONObject();
        oauthCode.put("header", headerMap);
        oauthCode.put("oauthCodeUrl", oauthCodeUrl);
        userOauthVO.setOauthCode(oauthCode);
        return userOauthVO;
    }


    @Override
    public OauthFlowVO oauthFlow(String connectorSign, JSONObject jsonObject) throws XbbException {
        OauthConnectorEntity oauthConnector = oauthConnectorModel.getByConnectorSign(connectorSign);
        if (Objects.isNull(oauthConnector)) {
            throw new XbbException(SsoErrorCodeEnum.API_ERROR_273003);
        }

        ParameterMapPojo parameterMapPojo = oauthParamHelp.getParameterMap(oauthConnector);
        Map<String, String> constantParameterMap = parameterMapPojo.getConstantParameterMap();
        Map<String, OauthCustomParamEntity> calculationCustomParameterMap = parameterMapPojo.getCalculationCustomParameterMap();
        OauthFlowVO oauthFlowVO = new OauthFlowVO();
        oauthCode(oauthConnector, jsonObject, constantParameterMap);
        if (userMatching(oauthConnector, constantParameterMap, oauthFlowVO)) {
            return oauthFlowVO;
        }
        accessToken(oauthConnector, constantParameterMap, calculationCustomParameterMap);
        if (userMatching(oauthConnector, constantParameterMap, oauthFlowVO)) {
            return oauthFlowVO;
        }
        identityAuthentication(oauthConnector, constantParameterMap, calculationCustomParameterMap);
        if (userMatching(oauthConnector, constantParameterMap, oauthFlowVO)) {
            return oauthFlowVO;
        }
        //走完所有的步骤，没有用户匹配参数
        throw new XbbException(SsoErrorCodeEnum.API_ERROR_273010);
    }

    /**
     * 授权码接收，三方回调授权码信息接收，更新固定参数信息parameterMap
     * @param oauthConnector
     * @param jsonObject
     * @param parameterMap
     * @return
     * @throws XbbException
     */
    public Map<String, String> oauthCode(OauthConnectorEntity oauthConnector, JSONObject jsonObject,
                                         Map<String, String> parameterMap) throws XbbException {
        OauthStepEntity oauthStep = oauthStepModel.getEntity(oauthConnector.getCorpid(),
                oauthConnector.getId(), StepTypeEnum.AUTH_CODE.getCode());
        if (Objects.isNull(oauthStep)) {
            LOG.info("oauthCode 授权步骤不存在或未启用!");
            return parameterMap;
        }
        List<OauthParamEntity> oauthParams = oauthParamModel.getOauthParams(oauthStep.getCorpid(), oauthStep.getId(),
                StageTypeEnum.RESPONSE.getCode(), EnableEnum.OPEN.getCode());
        LOG.info("oauthParams:" + oauthParams);
        requestParameterCover(jsonObject, oauthParams, parameterMap);
        return parameterMap;
    }

    /**
     * 回调地址接收参数映射
     * @param jsonObject
     * @param oauthParams
     * @param parameterMap
     */
    private void requestParameterCover(JSONObject jsonObject, List<OauthParamEntity> oauthParams,
                          Map<String, String> parameterMap) throws XbbException {
        for (OauthParamEntity oauthParam : oauthParams) {
            String attr = oauthParam.getAttr();
            String standardAttr = oauthParam.getStandardAttr();
            String value = jsonObject.getString(standardAttr);
            if (StringUtil.isEmpty(value)) {
                throw new XbbException(SsoErrorCodeEnum.API_ERROR_273018);
            }
            parameterMap.put(attr, "\"" + value + "\"");
        }
    }

    private Map<String, String> accessToken(OauthConnectorEntity oauthConnector, Map<String, String> parameterMap,
                                            Map<String, OauthCustomParamEntity> calculationCustomParameterMap) throws XbbException {
        //获取授权步骤配置
        OauthStepEntity oauthStep = oauthStepModel.getEntity(oauthConnector.getCorpid(),
                oauthConnector.getId(), StepTypeEnum.ACCESS_TOKEN.getCode());
        if (Objects.isNull(oauthStep)) {
            LOG.info("accessToken 授权步骤不存在或未启用!");
            return parameterMap;
        }
        String url = oauthStep.getUrl();
        if (StringUtil.isEmpty(url)) {
            throw new XbbException(SsoErrorCodeEnum.API_ERROR_273013);
        }
        Integer method = oauthStep.getMethod();
        Integer contentType = oauthStep.getContentType();
        List<OauthParamEntity> oauthParams = oauthParamModel.getOauthParams(oauthStep.getCorpid(), oauthStep.getId(),
                StageTypeEnum.REQUEST.getCode(), EnableEnum.OPEN.getCode());
        Map<String, String> headerMap = getHeaderParam(oauthParams, parameterMap, calculationCustomParameterMap);
        Map<String, Object> bodyMap = getBodyParam(oauthParams, parameterMap, calculationCustomParameterMap);
        String responseStr;
        try {
            if (Objects.equals(method, MethodEnum.GET.getCode())) {
                responseStr = OkHttpUtil.get(url, bodyMap, headerMap);
            } else {
                if (Objects.equals(contentType, ContentTypeEnum.FORM.getCode())) {
                    responseStr = OkHttpUtil.form(url, bodyMap, headerMap);
                } else {
                    responseStr = OkHttpUtil.postCommon(url, bodyMap, OkHttpUtil.APPLICATION_JSON_UTF8_VALUE, headerMap);
                }
            }
        } catch (Exception e) {
            throw new XbbException(SsoErrorCodeEnum.API_ERROR_273008);
        }
        try {
            responseAnalysis(oauthStep.getCorpid(), oauthStep.getId(), parameterMap, responseStr);
        } catch (XbbException e) {
            throw new XbbException(SsoErrorCodeEnum.API_ERROR_273016);
        }


        return parameterMap;
    }

    private Map<String, String> identityAuthentication(OauthConnectorEntity oauthConnector, Map<String, String> parameterMap,
                                                       Map<String, OauthCustomParamEntity> calculationCustomParameterMap) throws XbbException {
        //获取授权步骤配置
        OauthStepEntity oauthStep = oauthStepModel.getEntity(oauthConnector.getCorpid(),
                oauthConnector.getId(), StepTypeEnum.ID_AUTH.getCode());
        if (Objects.isNull(oauthStep)) {
            LOG.info("identityAuthentication 授权步骤不存在或未启用!");
            return parameterMap;
        }
        String url = oauthStep.getUrl();
        if (StringUtil.isEmpty(url)) {
            throw new XbbException(SsoErrorCodeEnum.API_ERROR_273013);
        }
        Integer method = oauthStep.getMethod();
        Integer contentType = oauthStep.getContentType();
        List<OauthParamEntity> oauthParams = oauthParamModel.getOauthParams(oauthStep.getCorpid(), oauthStep.getId(),
                StageTypeEnum.REQUEST.getCode(), EnableEnum.OPEN.getCode());
        Map<String, String> headerMap = getHeaderParam(oauthParams, parameterMap, calculationCustomParameterMap);
        Map<String, Object> bodyMap = getBodyParam(oauthParams, parameterMap, calculationCustomParameterMap);
        String responseStr = null;
        try {
            if (Objects.equals(method, MethodEnum.GET.getCode())) {
                responseStr = OkHttpUtil.get(url, bodyMap, headerMap);
            } else if (Objects.equals(method, MethodEnum.POST.getCode())) {
                String contentTypeStr = null;
                if (Objects.equals(contentType, ContentTypeEnum.FORM.getCode())) {
                    contentTypeStr = OkHttpUtil.APPLICATION_FORM_URLENCODED_VALUE;
                } else {
                    contentTypeStr = OkHttpUtil.APPLICATION_JSON_UTF8_VALUE;
                }
                responseStr = OkHttpUtil.postCommon(url, bodyMap, contentTypeStr, headerMap);
            }
        } catch (Exception e) {
            throw new XbbException(SsoErrorCodeEnum.API_ERROR_273009);
        }
        try {
            responseAnalysis(oauthStep.getCorpid(), oauthStep.getId(), parameterMap, responseStr);
        } catch (XbbException e) {
            throw new XbbException(SsoErrorCodeEnum.API_ERROR_273017);
        }
        return parameterMap;
    }

    private Map<String, String> responseAnalysis(String corpid, Long oauthStepId, Map<String, String> parameterMap,
                                                 String responseStr) throws XbbException {
        Map<String, String> responseMap = new HashMap<>();
        List<OauthParamEntity> oauthParams = oauthParamModel.getOauthParams(corpid, oauthStepId,
                StageTypeEnum.RESPONSE.getCode(), EnableEnum.OPEN.getCode());
        JSONObject responseJson = JSON.parseObject(responseStr);
        for (OauthParamEntity oauthParam : oauthParams) {
            String standardAttr = oauthParam.getStandardAttr();
            String attr = oauthParam.getAttr();
            String value = responseJson.getString(standardAttr);
            if (StringUtil.isEmpty(value)) {
                throw new XbbException(SsoErrorCodeEnum.API_ERROR_273015);
            }
            parameterMap.put(attr, "\"" + value + "\"");
            responseMap.put(attr, "\"" + value + "\"");
        }
        return parameterMap;
    }

    /**
     * 获取headerMap
     * @param oauthParams 对应阶段的request参数列表
     * @param parameterMap 参数常量
     * @param calculationCustomParameterMap 计算常量
     * @return
     */
    private Map<String, String> getHeaderParam(List<OauthParamEntity> oauthParams, Map<String, String> parameterMap,
                                          Map<String, OauthCustomParamEntity> calculationCustomParameterMap) throws XbbException {
        Map<String, String> headerMap = new HashMap<>();
        for (OauthParamEntity oauthParam : oauthParams) {
            Integer position = oauthParam.getPosition();
            if (!Objects.equals(position, PositionEnum.HEADER.getCode())) {
                continue;
            }
            String attr = oauthParam.getAttr();
            String standardAttr = oauthParam.getStandardAttr();
            String value = calculationHelp.getValue(standardAttr, parameterMap, calculationCustomParameterMap);
            headerMap.put(attr, value);
        }
        return headerMap;
    }

    /**
     * 获取bodyMap
     * @param oauthParams 对应阶段的request参数列表
     * @param parameterMap 参数常量
     * @param calculationCustomParameterMap 计算常量
     * @return
     */
    private Map<String, Object> getBodyParam(List<OauthParamEntity> oauthParams, Map<String, String> parameterMap,
                                          Map<String, OauthCustomParamEntity> calculationCustomParameterMap) throws XbbException {
        Map<String, Object> bodyParam = new HashMap<>();
        for (OauthParamEntity oauthParam : oauthParams) {
            Integer position = oauthParam.getPosition();
            if (!Objects.equals(position, PositionEnum.BODY.getCode())) {
                continue;
            }
            String attr = oauthParam.getAttr();
            String standardAttr = oauthParam.getStandardAttr();
            String value = calculationHelp.getValue(standardAttr, parameterMap, calculationCustomParameterMap);
            bodyParam.put(attr, value);
        }
        return bodyParam;
    }

    private boolean userMatching(OauthConnectorEntity oauthConnector, Map<String, String> parameterMap,
                                 OauthFlowVO oauthFlowVO) throws XbbException {
        //判断参数中是否有用户信息
        String identity_authentication = parameterMap.get(OauthFieldEnum.IDENTITY_AUTHENTICATION.getAttr());
        if (StringUtil.isEmpty(identity_authentication)) {
            return false;
        }
        identity_authentication = identity_authentication.substring(1, identity_authentication.length()-1);
        Integer accountRule = oauthConnector.getAccountRule();

        //匹配到用户
        XbbUserEntity user = getUser(oauthConnector.getCorpid(), accountRule, identity_authentication);

        if (Objects.isNull(user)) {
            throw new XbbException(SsoErrorCodeEnum.API_ERROR_273010);
        }
        //缓存状态、用户信息
        GenerateNonceVO generateNonceVO = generateNonce(user);
        //后一个步骤成功获取到用户信息时，生成用户的登录地址
        String loginUrl = generateNonceVO.getWebFrontUrl() + "auto-login.html?t="
                + URLEncodeUtils.encodeURL(generateNonceVO.getU())
                + "&nonce=" + URLEncodeUtils.encodeURL(generateNonceVO.getNonce());
        oauthFlowVO.setLoginUrl(loginUrl);
        return true;
    }

    /**
     * 通过IDP返回的唯一码，匹配获取到销帮帮用户的userId
     * @param corpid
     * @param accountRule
     * @param code
     * @return
     * @throws XbbException
     */
    private XbbUserEntity getUser(String corpid, Integer accountRule, String code) throws XbbException {
        String userId = null;
        if (Objects.equals(accountRule, AccountRuleEnum.CUSTOMIZE.getCode())) {
            OauthUserEntity oauthUser = oauthUserModel.getByCode(corpid, code);
            userId = Objects.isNull(oauthUser) ? null : oauthUser.getUserId();
            if (StringUtil.isEmpty(userId)) {
                return null;
            }
            return xbbUserModel.getByUserId(corpid, userId);
        }
        Map<String, Object> param = new HashMap<>();
        param.put("corpid", corpid);
        param.put("del", DelEnum.NORMAL.getDel());
        if (Objects.equals(accountRule, AccountRuleEnum.MOBILE.getCode())) {
            param.put("mobile", code);
        } else if (Objects.equals(accountRule, AccountRuleEnum.JOB_NUMBER.getCode())) {
            param.put("jobnumber", code);
        } else if (Objects.equals(accountRule, AccountRuleEnum.EMAIL.getCode())) {
            param.put("email", code);
        } else {
            throw new XbbException(SsoErrorCodeEnum.API_ERROR_273012);
        }
        List<XbbUserEntity> users = xbbUserModel.findEntitys(param);
        return CollectionsUtil.isEmpty(users) ? null : users.get(0);
    }

    @Override
    public GenerateNonceVO generateNonce(XbbUserEntity user) throws XbbException {
        if(user == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100025);
        }
        GenerateNonceVO generateNonceVO = new GenerateNonceVO();
        String corpid = user.getCorpid();
        String userId = user.getUserId();
        /*
        计算并存储nonce 和 u
         */
        try {
            // 分隔符从一个下划线改为四个下划线
            String userId_corpId = userId + "____" + corpid;
            //URLEncode
            String userId_corpIdEnCode = URLEncodeUtils.encodeURL(userId_corpId);
            String nonce = StringUtil.getRandomPassword(4, 6);
            String userDES = DesUtil.encrypt(userId_corpIdEnCode, ConfigConstant.DES_DEFAULT_KEY);
            paasRedisHelper.setValuePermanent(RedisPrefixConstant.USER_AUTO_LOGIN_NONCE, userId_corpId, nonce);
            generateNonceVO.setNonce(nonce);
            generateNonceVO.setU(userDES);
        } catch (Exception e) {
            LOG.error("generateNonce逻辑执行出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        // web服务地址
        generateNonceVO.setWebFrontUrl(proBaseConfig.getWebFrontUrl());
        //话务中心是否启用
        Integer moduleType = null;
        generateNonceVO.setModuleType(moduleType);
        return generateNonceVO;
    }

    /**
     * 截取第一个字符到最后一个字符的字符串
     * @param value
     * @return
     */
    private String removeQuotes(String value) {
        return value.substring(1, value.length()-1);
    }
}
